VSCode 使用教程 您所在的位置:网站首页 vscode js import报错 VSCode 使用教程

VSCode 使用教程

2024-03-02 02:54| 来源: 网络整理| 查看: 265

前言

js中导入公共模块,使用import的方式导入,用node运行js文件会出现Cannot use import statement outside a module的问题

问题描述

目录结构

└─src └─js └─ext.js └─main.js └─index.html

在ext.js 文件写一些公共方法

export const m = (function(){ return { hello: function(){ return 'hello ,,,,' }, world: function(){ return 'world !!!!!!!!' } } })()

在main.js 文件中导入并调用方法

import {m} from './ext.js' console.log(m.hello())

在html文件中,当js文件作为模块导入的时候,需在script标签声明type="module"类型

使用Open with live server方式打开html 是没有问题的。

如果我们想单独运行main.js 文件调试代码,使用node运行时,就会出现报错SyntaxError: Cannot use import statement outside a module

[Running] node "d:\code\web\src\js\main.js" (node:6900) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. d:\code\web\src\js\main.js:1 import {m} from './ext.js' ^^^^^^ SyntaxError: Cannot use import statement outside a module

从警告中可以看到,需要在package.json中加一个配置"type": "module"

添加 package.json 文件

初始化项目,快速生成package.json

npm init -y

在终端输入上面命令,会在项目根目录创建一个package.json文件

在package.json中加一个配置"type": "module"

{ "name": "web", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "type": "module" }

重新运行就不会报错了



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有